from django.shortcuts import redirect
from django.shortcuts import render_to_response
from django.template import RequestContext
import datetime
from forms import UserImageUploadForm
from upload.models import UploadedImage
from registration.models import UserProfile
from django.http import HttpResponseRedirect
from settings import MEDIA_ROOT

from registration.backends import get_backend

# Create your views here.
def image_upload(request):
    form = UserImageUploadForm(request.POST, request.FILES)
    if request.method == 'POST':
        if form.is_valid():
            file = request.FILES['imagepath']
            handle_uploaded_file(file)
            image = UploadedImage(imagepath = file.name,
                            rating = form.data['rating'],
                            owner = request.user,
                            times_visited = 0)
            image.save()
            return HttpResponseRedirect('/upload/thanks/')
    else:
        user_profile = UserProfile.objects.filter(username=request.user, is_uploader=True)
        if user_profile:
            form = UserImageUploadForm()
        else:
            context = RequestContext(request)
            return render_to_response('upload_fail.html',
                                      context_instance=context)
    context = RequestContext(request)
    return render_to_response('upload_form.html', {
            'form': form, 
            }, context_instance=context)

def handle_uploaded_file(f):
    destination = open ('%s/comics/%s' % (MEDIA_ROOT, f.name), 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

        
def sayThanks(request):
    context = RequestContext(request)
    return render_to_response('image_uploaded.html',context_instance=context)
    
    
    
    
    
    
    
    
    
    